package com.ruoyi.web.controller.business.sundry;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.customer.domain.JbCustomer;
import com.ruoyi.business.customer.domain.JbFollowupRecord;
import com.ruoyi.business.customer.service.JbCustomerService;
import com.ruoyi.business.customer.service.JbFollowupRecordService;
import com.ruoyi.business.order.domain.JbOrder;
import com.ruoyi.business.order.service.JbOrderService;
import com.ruoyi.business.sundry.domain.JbFastMenu;
import com.ruoyi.business.sundry.domain.JbNotification;
import com.ruoyi.business.sundry.domain.JbPerformance;
import com.ruoyi.business.sundry.domain.vo.JbStatisticsPerformanceVo;
import com.ruoyi.business.sundry.domain.vo.JbUserCommissionVo;
import com.ruoyi.business.sundry.domain.vo.PerformanceRankingVo;
import com.ruoyi.business.sundry.service.JbFastMenuService;
import com.ruoyi.business.sundry.service.JbNotificationService;
import com.ruoyi.business.sundry.service.JbPerformanceService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.web.controller.business.audit.factory.JbAuditFactory;
import com.ruoyi.web.controller.system.factory.SysDataScopeFactory;
import com.ruoyi.web.core.JoR;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工作台 Controller
 *
 * @author ruoyi
 * @date 2024-11-27
 */

@Api("工作台")
@RestController
@RequestMapping("/work_beance")
public class JbWorkBeanceController extends BaseController
{
    @Autowired
    private JbFastMenuService jbFastMenuService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private JbCustomerService jbCustomerService;
    @Autowired
    private JbFollowupRecordService jbFollowupRecordService;
    @Autowired
    private JbOrderService jbOrderService;
    @Autowired
    private JbPerformanceService jbPerformanceService;
    @Autowired
    private JbNotificationService jbNotificationService;
    @Autowired
    private JbAuditFactory jbAuditFactory;
    @Autowired
    private SysDataScopeFactory sysDataScopeFactory;

    /**
     * 获取本月统计
     */
    @ApiOperation("获取本月统计")
    @GetMapping(value = "/monthlyStatistics")
    public AjaxResult monthlyStatistics()
    {
        Map<String, BigDecimal> data = Maps.newHashMap();
        // 获取当月的开始时间
        LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).with(LocalTime.MIDNIGHT);
        Long userId = getUserId();
        // 新增客户
        long customerAdd = jbCustomerService.count(Wrappers.lambdaQuery(JbCustomer.class)
                .eq(JbCustomer::getBusinessManagerId, userId)
                .ge(JbCustomer::getCreateTime, startOfMonth));
        // 新增跟进记录
        long followupRecordAdd = jbFollowupRecordService.count(Wrappers.lambdaQuery(JbFollowupRecord.class)
                .eq(JbFollowupRecord::getStaffId, userId)
                .eq(JbFollowupRecord::getDataType, Constants.PUBLIC_NUMBER_1)
                .ge(JbFollowupRecord::getCreateTime, startOfMonth));
        // 新增订单和成交金额
        QueryWrapper<JbOrder> orderWrapper = new QueryWrapper();
        orderWrapper.select(" sum(order_total_amount) as orderTotalAmount" +
                ",count(1) as createBy ");
        orderWrapper.lambda().eq(JbOrder::getCreateBy, userId)
                .eq(JbOrder::getIsProcessEnd, Constants.PUBLIC_NUMBER_1)//流程完结
                .ge(JbOrder::getCreateTime, startOfMonth);
        JbOrder jbOrderOne = jbOrderService.getOne(orderWrapper, false);
        BigDecimal orderAdd = BigDecimal.ZERO;
        BigDecimal orderTotalAmount = BigDecimal.ZERO;
        if (ObjectUtils.isNotEmpty(jbOrderOne))
        {
            orderTotalAmount = jbOrderOne.getOrderTotalAmount();
            orderAdd = new BigDecimal(jbOrderOne.getCreateBy());
        }
        data.put("customerAdd", new BigDecimal(customerAdd));
        data.put("followupRecordAdd", new BigDecimal(followupRecordAdd));
        data.put("orderAdd", orderAdd);
        data.put("orderTotalAmount", orderTotalAmount);
        return success(data);
    }

    @ApiOperation("获取快速菜单")
    @GetMapping(value = "/fastMenuList")
    public AjaxResult fastMenuList()
    {
        Long userId = getUserId();
        List<JbFastMenu> list = jbFastMenuService.list(Wrappers.lambdaQuery(JbFastMenu.class)
                .eq(JbFastMenu::getCreateBy, userId));
        List<SysMenu> menuList = Lists.newArrayList();
        if (ObjectUtils.isNotEmpty(list))
        {
            List<Long> collect = list.stream().map(JbFastMenu::getMenuId).collect(Collectors.toList());
            menuList = menuService.selectMenuList(userId);
            if (ObjectUtils.isNotEmpty(menuList))
            {
                menuList=menuList.stream().filter(a -> collect.contains(a.getMenuId())).collect(Collectors.toList());
                Map<Long, String> menuMap = list.stream().collect(Collectors.toMap(JbFastMenu::getMenuId, JbFastMenu::getPath));
                menuList.forEach(a ->
                {
                    if (StringUtils.isNotBlank(menuMap.get(a.getMenuId())))
                    {
                        a.setPath(menuMap.get(a.getMenuId()));
                    }
                });
            }
        }
        return success(menuList);
    }

    @ApiOperation("修改快速菜单")
    @PostMapping(value = "/editFastMenu")
    public AjaxResult editFastMenu(@RequestBody List<JbFastMenu> jbFastMenu)
    {
        Long userId = getUserId();
        jbFastMenuService.remove(Wrappers.lambdaQuery(JbFastMenu.class)
                .eq(JbFastMenu::getCreateBy, userId));
        if (ObjectUtils.isNotEmpty(jbFastMenu))
        {
            return success(jbFastMenuService.saveBatch(jbFastMenu));
        }
        return error();
    }

    /**
     * 获取登录用户角色菜单
     *
     * @return
     */
    @ApiOperation("获取登录用户菜单")
    @GetMapping(value = "/menuList")
    public AjaxResult menuList()
    {
        // 类型（M目录 C菜单 F按钮）
        // 当前用户的菜单数据
        Long userId = getUserId();
        List<SysMenu> menus = menuService.selectMenuList(userId);
        // 设置的快速菜单
        List<Long> menuId = jbFastMenuService.list(Wrappers.lambdaQuery(JbFastMenu.class)
                        .eq(JbFastMenu::getCreateBy, userId).select(JbFastMenu::getMenuId))
                .stream().map(JbFastMenu::getMenuId).collect(Collectors.toList());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", menuId);
        ajax.put("menus", menuService.buildMenuTreeSelect(menus));
        return ajax;
    }

    /**
     * 获取业绩目标
     *
     * @return
     */
    @ApiOperation("获取业绩目标")
    @GetMapping(value = "/performanceData")
    public AjaxResult performanceData(String type)
    {
        // 默认本年的开始时间
        LocalDateTime[] times = DateUtils.getTimes(Constants.CUSTOMER_TYPE_1001);
        if (Constants.CUSTOMER_TYPE_1009.equals(type))
        {
            times = DateUtils.getTimes(Constants.CUSTOMER_TYPE_1009);
        }else if (Constants.CUSTOMER_TYPE_1005.equals(type))
        {
            times = DateUtils.getTimes(Constants.CUSTOMER_TYPE_1005);
        }
        // 本年的开始时间
        LocalDateTime startOfMonth = LocalDateTime.now().withDayOfYear(1).with(LocalTime.MIDNIGHT);
        Long userId = getUserId();
        // 年度目标的成交金额
        JbPerformance one = jbPerformanceService.getOne(Wrappers.lambdaQuery(JbPerformance.class)
                .eq(JbPerformance::getRelatedId, userId)
                .eq(JbPerformance::getFinancialYear, startOfMonth.getYear())
                .eq(JbPerformance::getTargetType, Constants.CUSTOMER_TYPE_1001)
                .eq(JbPerformance::getPerformanceType, Constants.PUBLIC_NUMBER_2), false);
        BigDecimal annualTarget = BigDecimal.ZERO;
        BigDecimal annualTargetTransform = BigDecimal.ZERO;
        String targetUnit="";
        if (ObjectUtils.isNotNull(one))
        {
            annualTarget = one.getAnnualTarget();
            targetUnit = one.getTargetUnit();
            //如果targetUnit单位是万，则把annualTarget乘以万
            if (Constants.CUSTOMER_TYPE_1001.equals(targetUnit))
            {
                annualTargetTransform = annualTarget.multiply(new BigDecimal(10000));
            }
            if (Constants.CUSTOMER_TYPE_1002.equals(targetUnit))
            {
                annualTargetTransform = annualTarget.multiply(new BigDecimal(100000000));
            }

        }
        // 年度成交金额
        QueryWrapper<JbOrder> orderWrapper = new QueryWrapper();
        orderWrapper.select(" sum(order_total_amount) as orderTotalAmount");
        orderWrapper.lambda().eq(JbOrder::getCreateBy, userId)
                .eq(JbOrder::getIsProcessEnd, Constants.PUBLIC_NUMBER_1)//流程完结
                // .ge(JbOrder::getCreateTime, startOfMonth)
                .ge(JbOrder::getCreateTime, times[0])
                .le(JbOrder::getCreateTime, times[1])
        ;
        JbOrder jbOrderOne = jbOrderService.getOne(orderWrapper, false);
        BigDecimal orderTotalAmount = BigDecimal.ZERO;
        if (ObjectUtils.isNotEmpty(jbOrderOne)) orderTotalAmount = jbOrderOne.getOrderTotalAmount();
        // 赋值
        Map<String, Object> mapData = Maps.newHashMap();
        mapData.put("annualTarget", annualTarget);
        mapData.put("orderTotalAmount", orderTotalAmount);
        mapData.put("targetUnit", targetUnit);
        mapData.put("annualTargetTransform", annualTargetTransform);
        return success(mapData);
    }

    /**
     * 员工业绩排行榜
     *
     * @return
     */
    @ApiOperation("员工业绩排行榜")
    @GetMapping(value = "/performanceRanking")
    public TableDataInfo performanceRanking(PageParam pageParam)
    {
        IPage<PerformanceRankingVo> page = jbPerformanceService.performanceRanking(pageParam);
        return JoR.getDataTable(page);
    }
    /**
     * 员工业绩排行数据
     *
     * @return
     */
    @ApiOperation("员工业绩排行数据")
    @GetMapping(value = "/performanceRankingData")
    public AjaxResult performanceRankingData(PageParam pageParam)
    {
        List<JbUserCommissionVo> list = jbPerformanceService.performanceRankingData(pageParam,new JbUserCommissionVo());
        return success(list);
    }

    /**
     * 跟进计划
     */
    @ApiOperation("跟进计划")
    @GetMapping(value = "/followupList")
    public TableDataInfo followupList(PageParam pageParam)
    {
        JbFollowupRecord jbFollowupRecord = new JbFollowupRecord();
        jbFollowupRecord.setDataType(Constants.PUBLIC_NUMBER_0);
        jbFollowupRecord.setStaffId(getUserId());
        return JoR.getDataTable(jbFollowupRecordService.followupList(pageParam, jbFollowupRecord));
    }

    /**
     * 通知列表
     */
    @ApiOperation("通知列表")
    @GetMapping(value = "/notificationList")
    public TableDataInfo notificationList(PageParam pageParam)
    {
        IPage<JbNotification> page = jbNotificationService.page(pageParam.b(),
                Wrappers.lambdaQuery(JbNotification.class)
                        .eq(JbNotification::getRecipientId, getUserId())
                        .orderByDesc(JbNotification::getId));
        return JoR.getDataTable(page);
    }

    /**
     * 未读通知数量
     */
    @ApiOperation("未读通知数量")
    @GetMapping(value = "/notificationNumber")
    public AjaxResult notificationNumber(PageParam pageParam)
    {

        long count = jbNotificationService.count(Wrappers.lambdaQuery(JbNotification.class)
                .eq(JbNotification::getRecipientId, getUserId())
                .eq(JbNotification::getStatus, Constants.PUBLIC_NUMBER_1)
        );
        return success(count);
    }

    /**
     * 待办事项列表
     */
    @ApiOperation("待办事项列表")
    @GetMapping("/backlogItemList")
    public AjaxResult backlogItemList(PageParam param, JbStatisticsPerformanceVo jbPerformance)
    {
        Long userId = getUserId();
        //角色数据权限
        List<Long> roleData=sysDataScopeFactory.fnListDataScope(Constants.PUBLIC_NUMBER_0.toString());
        // 待跟进客户
        long count = jbFollowupRecordService.count(Wrappers.lambdaQuery(JbFollowupRecord.class)
                // .in(ObjectUtils.isNotEmpty(roleData),JbFollowupRecord::getStaffId, roleData)
                .eq(JbFollowupRecord::getStaffId, userId)
                .eq(JbFollowupRecord::getDataType, Constants.PUBLIC_NUMBER_0)
                .eq(JbFollowupRecord::getTaskStatus, Constants.JBFOLLOWUPRECORD_TASKSTATUS_1003));
        // 待办查询，目前查全量的
        JSONObject taskCount = jbAuditFactory.taskListStatistics(param);
        taskCount.put("customerStatistics", count);
        return success(taskCount);
    }
}
